﻿using Eneta.Portal.Common.Dto;
using Microsoft.SharePoint;

namespace Eneta.Portal.Common
{
    /// <summary>
    /// Class for logging administrative activities.
    /// </summary>
    public static class ActivityLogger
    {
        /// <summary>
        /// Logs the activity.
        /// </summary>
        /// <param name="activity">The activity to be logged.</param>
        public static void LogActivity(AdminActivityDto activity)
        {
            var siteId = SPContext.Current.Site.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (var site = new SPSite(siteId))
                using (var web = site.OpenWeb())
                {
                    var list = web.Lists["AdminActivities"];
                    var item = list.Items.Add();

                    var fieldId = list.Fields.GetFieldByInternalName("URL").Id;
                    item[fieldId] = list.ParentWeb.Url + activity.Url;
                    fieldId = list.Fields.GetFieldByInternalName("Module").Id;
                    item[fieldId] = activity.Module;

                    fieldId = list.Fields.GetFieldByInternalName("CurrentEditor").Id;
                    var user = web.SiteUsers[activity.CurrentEditor];
                    item[fieldId] = user; // new SPFieldUserValue(item.Web,);
                    fieldId = list.Fields.GetFieldByInternalName("CurrentStatus").Id;
                    item[fieldId] = activity.CurrentStatus.ToString();
                    fieldId = list.Fields.GetFieldByInternalName("CurrentTimeStamp").Id;
                    item[fieldId] = activity.CurrentTimeStamp;

                    fieldId = list.Fields.GetFieldByInternalName("PreviousEditor").Id;
                    user = web.SiteUsers[activity.PreviousEditor];
                    item[fieldId] = user;
                    fieldId = list.Fields.GetFieldByInternalName("PreviousStatus").Id;
                    item[fieldId] = activity.PreviousStatus.ToString();
                    fieldId = list.Fields.GetFieldByInternalName("PreviousTimeStamp").Id;
                    item[fieldId] = activity.PreviousTimeStamp;

                    item.Update();
                    list.Update();

                }
            });
        }

    }
}
